package com.dbutils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapListHandler;

public class MapListExample {

	@SuppressWarnings("rawtypes")
	public static void main(String[] args) {
		String url = "jdbc:mysql://localhost/test_java";
		String username="dong";
		String password="xiaodong";
		String sql = "select id, name, phone, email from dbutils01_guestbook order by id desc ";
		DbUtils.loadDriver("com.mysql.jdbc.Driver");
		try {
			Connection conn = DriverManager.getConnection(url, username, password);
			QueryRunner qr = new QueryRunner();
			List result = (List) qr.query(conn, sql, new MapListHandler());
			DbUtils.close(conn);
			Map map = null;
			for (int i = 0; i < result.size(); i++) {
				map = (Map) result.get(i);
				System.out.print("id:" + map.get("id") + "\t");
				System.out.print("name:" + map.get("name") + "\t");
				System.out.print("phone:" + map.get("phone") + "\t");
				System.out.println("email:" + map.get("email"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

}
